package cn.com.infcn.monitor.task.impl;

import org.apache.mina.core.session.IoSession;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.infcn.monitor.bean.IFCCpu;
import cn.com.infcn.monitor.bean.IFCResponseBean;
import cn.com.infcn.monitor.util.IFCBeanUtils;
import cn.com.infcn.monitor.util.IFCMinitorConstanst;

/**
 * 获取系统cpu信息，返回一个cpu信息的数组
 * 
 * @author jjs
 *
 */
public class CpuTask extends BaseTask {

	private static Logger logger = LoggerFactory.getLogger(CpuTask.class);

	public CpuTask(IoSession session, Object message) {
		super(session, message);
	}

	@Override
	public void execute() throws Exception {
		IFCResponseBean result = cpu();
		sendResponse(result);
	}

	private IFCResponseBean cpu() throws SigarException {
		IFCResponseBean result = new IFCResponseBean();

		try {
			Sigar sigar = new Sigar();
			CpuInfo cpuInfos[] = sigar.getCpuInfoList();
			CpuPerc cpuPercs[] = sigar.getCpuPercList();
			IFCCpu[] ifcCpus = new IFCCpu[cpuInfos.length];

			for (int i = 0; i < cpuInfos.length; i++) {// 不管是单块CPU还是多CPU都适用
				// cpu 信息
				CpuInfo cpuInfo = cpuInfos[i];
				// cpu 使用率信息
				CpuPerc cpuPerc = cpuPercs[i];
				IFCCpu ifcCpu = new IFCCpu();
				IFCBeanUtils.copyProperties(cpuInfo, ifcCpu);
				IFCBeanUtils.copyProperties(cpuPerc, ifcCpu);

				ifcCpus[i] = ifcCpu;
			}

			result.setResult(ifcCpus);
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_OK);
		} catch (Exception e) {
			logger.error(e.getMessage());
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_ERROR);
			result.setResponseMsg(e.getMessage());
		}
		return result;
	}

	public static void main(String[] args) throws SigarException {
		CpuTask t = new CpuTask(null, null);
		IFCResponseBean result = t.cpu();
		IFCCpu[] cpus = (IFCCpu[]) result.getResult();
		IFCCpu cpu = cpus[0];
		System.out.println(cpu.getMhz());
	}

}
